<template>
    <el-card class="card f fv">
        <div class="f fac fpj">
            <div class="title">养殖管理</div>
            <div class="operation">
                <el-button type="primary" @click="openDialog(null, '添加')">添加动物</el-button>
            </div>
        </div>
        <!-- 搜索条件 -->
        <el-form style="margin-top: 0.12rem;" :model="data.searchform" :inline="true">
            <el-form-item label="动物名称">
                <el-input clearable style="width: 2rem;" @clear="getList(true)" v-model="data.searchform.name"
                    placeholder="请输入动物名称" />
            </el-form-item>
            <el-form-item label="养殖农场">
                <el-select style="width: 2rem;" clearable @change="getList(true)" v-model="data.searchform.type"
                    placeholder="请选择农场">
                    <el-option v-for="item in data.landList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="">
                <el-button type="primary" @click="getList(true)">搜索</el-button>
            </el-form-item>
        </el-form>

        <!-- 表格 -->
        <el-table :data="data.tableList" :height="data.tableHeight" v-loading="data.tableLoading" stripe class="table">
            <el-table-column prop="name" align="center" label="名称" />
            <el-table-column prop="land_id" align="center" label="农场">
                <template #default="scope">
                    {{ data.landList.filter(item => item.id == scope.row.land_id)[0]?.name }}
                </template>
            </el-table-column>
            <el-table-column prop="area" align="center" label="养殖面积" />
            <el-table-column prop="num" align="center" label="养殖数量" />
            <el-table-column prop="create_time" align="center" label="养殖时间">
                <template #default="scope">
                    <span>{{ scope.row.create_time && utils.formatDate(new Date(scope.row.create_time).getTime(), 'Y-M-D H:I:S') }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="feed_time" align="center" label="喂养时间" />
        </el-table>

        <!-- 分页 -->
        <el-pagination background style="margin-top: 0.16rem;" layout="->, total, sizes, prev, pager, next" :pager-count="5"
            v-model:current-page="data.pageNum" v-model:page-size="data.pageSize" :total="data.total"
            @size-change="getList()" @current-change="getList()" />

        <!-- 抽屉/弹框 -->
        <el-drawer v-model="dialogData.dialogVisible" :title="dialogData.dialogTitle" direction="rtl" @close="closeDialog">
            <div class="content">
                <el-form :model="dialogData.form" label-postion="left" label-width="0.8rem" :rules="dialogData.formRules" hide-required-asterisk ref="refForm">
                    <el-form-item label="动物名称" prop="name">
                        <el-input v-model="dialogData.form.name" placeholder="请输入动物名称" />
                    </el-form-item>
                    <el-form-item label="农场" prop="land_id">
                        <el-select v-model="dialogData.form.land_id" placeholder="请选择农场">
                            <el-option v-for="item in data.landList" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                        <span style="margin-left: 0.1rem;" v-if="dialogData.form.land_id">
                            可养殖面积:<span style="color: red;">{{ dialogData.animalArea }}</span>㎡
                        </span>
                    </el-form-item>
                    <el-form-item label="养殖面积" prop="area">
                        <el-input v-model.number="dialogData.form.area" placeholder="请输入养殖面积">
                            <template #append>㎡</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="养殖数量" prop="num">
                        <el-input v-model="dialogData.form.num" placeholder="请输入动物数量" />
                    </el-form-item>
                    <el-form-item label="喂养时间" prop="feed_time">
                        <div class="f fac" style="width: 100%;">
                            <el-time-picker value-format="HH:mm:ss" style="width: 1.4rem;" v-model="dialogData.form.morning" placeholder="早上" />
                            <el-time-picker value-format="HH:mm:ss" style="width: 1.4rem; margin: 0 0.2rem;" v-model="dialogData.form.nooning" placeholder="中午" />
                            <el-time-picker value-format="HH:mm:ss" style="width: 1.4rem;" v-model="dialogData.form.evening" placeholder="晚上" />
                        </div>
                    </el-form-item>
                </el-form>
                <div class="footer">
                    <el-button type="primary" @click="submit">确定</el-button>
                    <el-button @click="closeDialog">取消</el-button>
                </div>
            </div>
        </el-drawer>
    </el-card>
</template>

<script setup>
import { ref, onMounted, reactive, watch, watchEffect, onUnmounted } from 'vue'
import http from '@/api/home'
import utils from '@/utils/utils'
import socket from '@/plugin/socket'

const refForm = ref()

// 自定义校验规则
const validateArea = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入面积'))
  } else if (value > dialogData.animalArea) {
    callback(new Error('该农场养殖面积不足'))
  } else {
    callback()
  }
}
const validateFeedTime = (rule, value, callback) => {
    dialogData.form.feed_time = `${dialogData.form.morning},${dialogData.form.nooning},${dialogData.form.evening}`
    let timeStamp = dialogData.form.feed_time.split(',')
    console.log(timeStamp);
    if (timeStamp.length < 3) {
        callback(new Error('请选择喂养时间'))
    } else {
        if (timeStamp.includes('undefined') || timeStamp.includes('null')) {
            callback(new Error('请选择喂养时间'))
        } else {
            callback()
        }   
    }
}

// 数据集
const data = reactive({
    // 搜索表单对象
    searchform: {},
    // 表格数据
    tableList: [],
    // 表格高度
    tableHeight: 0,
    // 表格加载
    tableLoading: false,
    // 分页 
    pageNum: 1,
    pageSize: 20,
    total: 0,
    // 农场列表
    landList: [],
})

// 弹框
const dialogData = reactive({
    // 是否显示
    dialogVisible: false,
    // 标题
    dialogTitle: '',
    // 表单数据 
    form: {},
    // 校验规则
    formRules: {
        name: [{ required: true, message: '请输入动物名称', trigger: 'blur' }],
        land_id: [{ required: true, message: '请选择农场', trigger: 'change' }],
        area: [{ required: true, validator: validateArea, trigger: 'blur' }],
        num: [{ required: true, message: '请输入养殖数量', trigger: 'blur' }],
        feed_time: [{ required: true, validator: validateFeedTime, trigger: 'change' }],

    },
})

onMounted(() => {
    getLandList()
    getList()
    socket.connect()
})

// 获取农场列表
const getLandList = () => {
    http.landList({
        pageNum: 1,
        pageSize: 10000,
        type: 2
    }).then(res => {
        data.landList = res.data.records
    })
}

// 获取列表
const getList = (reset = false) => {
    if (reset) data.pageNum = 1
    data.tableLoading = true
    http.animalList({
        ...data.searchform,
        pageNum: data.pageNum,
        pageSize: data.pageSize
    }).then(res => {
        data.tableLoading = false
        data.tableList = res.data.records
        data.total = res.data.total
    }).finally(() => {
        data.tableLoading = false
    })
}

// 打开对话框
const openDialog = (row, title) => {
    dialogData.dialogVisible = true
    if (row) {
        dialogData.form = { ...row }
    } else {
        dialogData.form = {}
    }
    dialogData.dialogTitle = title
}

// 关闭对话框
const closeDialog = () => {
    dialogData.dialogVisible = false;
    refForm.value.resetFields();
    dialogData.form = {}
}

//提交
const submit = () => {
    refForm.value.validate((valid) => {
        if (valid) {
            // dialogData.form.feed_time = `${dialogData.form.morning},${dialogData.form.nooning},${dialogData.form.evening}`
            if (dialogData.dialogTitle == '添加') {
                http.animalAdd(dialogData.form).then(res => {
                    ElMessage({ type: 'success', message: res.message })
                    dialogData.dialogVisible = false
                    getList()
                })
            } else {
                
            }
        }
    })
}

// socket事件
socket.on("connect", () => {
    console.log("socket connect success")
})
socket.on("message", (message) => {
    ElNotification({
        title: '提示',
        dangerouslyUseHTMLString: true,
        message: message.data,
        duration: 0,
    })
})
socket.on("error", (error) => {
    console.error("socket连接失败", error);
})
socket.on("disconnect", () => {
    console.log("socket disconnect");
})

onUnmounted(() => {
    socket.disconnect()
})


watch(() => dialogData.form.land_id, (newValue, oldValue) => {
    if (newValue) {
        // 选择的农场
        let land = data.landList.filter(item => item.id == dialogData.form.land_id)[0]
        if (!land) {
            dialogData.animalArea = ''
            return
        }
        // 农场面积
        let landArea = land.area
        // 农场可种植面积
        let animalArea = landArea
        data.tableList.forEach(item => {
            if (item.land_id == land.id) {
                animalArea -= item.area
            }
        });
        dialogData.animalArea = animalArea
    }
}, { deep: true })

// 设置表格高度
const setTableHeight = () => {
    let tableH = 320 // 距离下方的距离 
    let tableHeightDetail = window.innerHeight - tableH
    if (tableHeightDetail <= 400) {
        data.tableHeight = 400
    } else {
        data.tableHeight = window.innerHeight - tableH
    }
}
watchEffect(() => setTableHeight())

</script>

<style lang="scss" scoped>
.card {
    box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.2);
    margin-top: 0.14rem;
    height: calc(100vh - 0.68rem - 0.7rem);

    .title {
        font-size: 0.2rem;
        font-weight: bold;
        color: #000;
        padding-bottom: 0.1rem;
        border-bottom: 4px solid $ncpColor;
    }

    .role-input {
        width: 2rem;
        margin-right: 0.2rem;
    }

    .table {
        width: 100%;

        .table-sale {
            color: $helpColor;
        }

        .table-info {
            color: #9CA3AF;
            font-size: 0.12rem;
        }
    }

    .table-edit {
        color: $otherColor;
        margin-right: 0.2rem;
        cursor: pointer;

        &:hover {
            text-decoration: underline;
        }
    }

    .disabled {
        pointer-events: none;
        opacity: 0.8;
    }

    .table-delete {
        color: $helpColor;
        cursor: pointer;

        &:hover {
            text-decoration: underline;
        }
    }

    :deep(.el-drawer__title) {
        font-size: 0.16rem;
    }

    .content {
        position: relative;
        height: 100%;
        .map {
            width: 100%;
            height: 5.6rem;
        }

        .footer {
            position: absolute;
            bottom: 0;
            left: 0;
        }
    }
    .yield {
        .name {
            font-size: 0.16rem;
            color: $ncpColor;
            margin-right: 0.1rem;
        }
        .yieldNum {
            font-size: 0.2rem;
            color: $ncpColor;
        }
    }

}</style>